package com.panshi.config;

//shiro 自定义 userrealm

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.panshi.entity.SysAdminApi;
import com.panshi.service.SysClientService;
import com.panshi.util.CheckUtil;
import com.panshi.utils.AdminInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private SysClientService sysClientService;

    @Autowired
    private AdminInfo adminInfo;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了 ===》授权");
        //SimpleAuthenticationInfo
        //SimpleAuthorizationInfo
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //info.addStringPermission("user:add");

        //获取当前登录这个对象
        Subject subject = SecurityUtils.getSubject();
        SysAdminApi currentUser = (SysAdminApi) subject.getPrincipal();   //获取对象\
        System.out.println("--------------权限---------------");
        SysAdminApi adminApi = adminInfo.getAdminInfo(currentUser);
        if(currentUser.getFunctionTList()!=null){
            currentUser.getFunctionTList().forEach(item->{
                if(item!=null){
                    info.addStringPermission(item.getFunctionUrl());
                }
            });
        }
        //info.addStringPermission(currentUser.getPerms());
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了 ===》认证");
        UsernamePasswordToken userToken = (UsernamePasswordToken)token;
        //用户 密码 数据
        //获取真实数据
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("name",userToken.getUsername());
        String username = userToken.getUsername();
        boolean email = CheckUtil.isEmail(username);
        boolean mobile = CheckUtil.isMobile(username);
        System.out.println(email+" "+mobile);
        SysAdminApi admint = null;
        if(email){
            admint = sysClientService.getAdminEmail(username);
        }else if(mobile){
            admint = sysClientService.getAdminPhone(username);
        }
        if(admint==null){
            return null;
        }
        if(admint.getAdminId()==null){
            return null;
        }
        System.out.println("登录用户信息"+admint);

        //密码认证：shiro做
//        return new SimpleAuthenticationInfo(list.get(0),list.get(0).getPassword(),"");
        return new SimpleAuthenticationInfo(admint,admint.getAdminPassword(),"");
    }
}
